/*line.c*/
#include "cineplex.h"

void Line_Enqueue(int type, int index, int cust)
{
	struct Line * line;
	if(type == T_TICKETCLERK)
	{
		line = tixLines;
	}else if(type == T_FOODCLERK)
	{
		line = foodLines;
	}else if(type == T_TICKETTAKER)
	{
		line = entryLines;
	}
	
	if(line[index].isOpen == 0) return;
	line[index].customers[line[index].length] = cust;
	line[index].length = line[index].length + 1;
	if(type == T_TICKETCLERK)
	{
		Acquire(tixClerks[index].msgLock);
		Signal(tixClerks[index].sleepCon, tixClerks[index].msgLock);
		Release(tixClerks[index].msgLock);
	}else if(type == T_FOODCLERK)
	{
		Acquire(foodClerks[index].msgLock);
		Signal(foodClerks[index].sleepCon, foodClerks[index].msgLock);
		Release(foodClerks[index].msgLock);
	}else if(type == T_TICKETTAKER)
	{
		Acquire(tixTakers[index].msgLock);
		Signal(tixTakers[index].sleepCon, tixTakers[index].msgLock);
		Release(tixTakers[index].msgLock);
	}
}

void Line_Dequeue(int type, int index, int cust)
{
	struct Line * line;
	if(type == T_TICKETCLERK)
	{
		line = tixLines;
	}else if(type == T_FOODCLERK)
	{
		line = foodLines;
	}else if(type == T_TICKETTAKER)
	{
		line = entryLines;
	}
	
	if(line[index].isOpen == 0) return;
	
	Acquire(loopLock);
	for(i = 0; i < line[index].length; i++)
	{
		if(line[index].customers[i] == cust)
		{
			break;
		}
	}
	for(k = i; k < MAX_CUSTOMERS/MAX_GROUP_SIZE; k++)
	{
		/*movin on up*/
		line[index].customers[k] = line[index].customers[k+1];
	}
	line[index].customers[MAX_CUSTOMERS/MAX_GROUP_SIZE] = -1;
	Release(loopLock);
}

int Line_FindInLine(int type, int index, int cust)
{
	struct Line * line;
	if(type == T_TICKETCLERK)
	{
		line = tixLines;
	}else if(type == T_FOODCLERK)
	{
		line = foodLines;
	}else if(type == T_TICKETTAKER)
	{
		line = entryLines;
	}
	
	if(line[index].isOpen == 0) return MAX_CUSTOMERS;
	
	line[index].output = -1;	
	Acquire(loopLock);
	for(i = 0; i < line[index].length; i++)
	{
		if(line[index].customers[i] == cust)
		{
			line[index].output = i;
			break;
		}
	}
	Release(loopLock);
	return line[index].output;
}

int Line_getSize(int type, int index)
{
	struct Line * line;
	if(type == T_TICKETCLERK)
	{
		line = tixLines;
	}else if(type == T_FOODCLERK)
	{
		line = foodLines;
	}else if(type == T_TICKETTAKER)
	{
		line = entryLines;
	}
	if(line[index].isOpen == 0) return -1;
	return line[index].length;
}

void Line_Clear(int type, int index)
{
	struct Line * line;
	if(type == T_TICKETCLERK)
	{
		line = tixLines;
	}else if(type == T_FOODCLERK)
	{
		line = foodLines;
	}else if(type == T_TICKETTAKER)
	{
		line = entryLines;
	}
	
	line[index].length = 0; /*no need to actually clear the list*/
}
